<template>
  <div>
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          :model="loginForm"
          ref="ruleFormRef"
          :rules="rules"
          label-width="120px"
          class="myFrom"
        >
          <h1>hello</h1>
          <h2>欢迎来到我的商城</h2>
          <el-form-item label="账号" prop="username">
            <el-input v-model="loginForm.username" :prefix-icon="User" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" :prefix-icon="Lock" />
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" @click="login" :loading="loading">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import {
  ref,
  reactive,
  toRefs,
  onBeforeMount,
  onMounted,
  watchEffect,
  computed,
} from 'vue'
import { useRouter } from 'vue-router'
import userUserStore from '@/store/modules/user'
import { ElNotification } from 'element-plus'

let useStore = userUserStore()
const loginForm = reactive({
  username: 'admin',
  password: '111111',
})
let loading = ref(false)
const validateUsername = (rule, value, callback) => {
  if (value.length >= 5) {
    callback()
  } else {
    callback(new Error('账号长度至少五位'))
  }
  console.log(rule)
}
// 表单配置
const rules = {
  username: [
    // { required: true, message: '用户名不能为空', trigger: 'blur' },
    // {
    //   required: true,
    //   min: 6,
    //   max: 6,
    //   message: '长度在 6 个字符',
    //   trigger: 'change',
    // },
    { trigger: 'change', validator: validateUsername },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 6, max: 6, message: '长度在 6 个字符', trigger: 'change' },
  ],
}
const $router = useRouter()

let ruleFormRef = ref()
const login = async () => {
  loading.value = true
  await ruleFormRef.value.validate()
  console.log(loginForm)
  try {
    let res = await useStore.userLogin(loginForm)
    console.log(res, 'mlpnko')

    $router.push('/')
    ElNotification({
      type: 'success',
      message: '登录成功',
    })
    loading.value = false
  } catch (error) {
    ElNotification({
      type: 'error',
      message: error.message,
    })
    loading.value = false
  }
}
</script>
<style scoped lang="scss">
.myFrom {
  width: 80%;
}
</style>
